// miniprogram/pages/my/addAdress.js
const app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        addressInfo: {}
    },
    formSubmit(e) {
        console.log('form发生了submit事件，携带数据为：', e.detail.value)
        let data = e.detail.value;
        if (!this.checkPhoneAndPostCode(data)) {
            wx.showToast({
                title: '请检查手机和邮编是否正确!',
                icon:'none'
            })
            return
        }
        const db = wx.cloud.database()
        try {
            let value = wx.getStorageSync('userAddress')
            if (value) {
                // Do something with return value
                value.push(data)
                wx.setStorageSync('userAddress', value)
            } else {
                wx.setStorageSync('userAddress', [data])
            }
            wx.showModal({
                title: '提示',
                content: '添加成功!',
                showCancel: false,
                success: () => {
                    wx.reLaunch({
                        url: "/pages/my/index"
                    });
                }
            })
        } catch (e) {
            console.log(e)
            // Do something when catch error
            return false
        }
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        if (options && options.addressIndex) {
            wx.getStorage({
                key: 'userAddress',
                success: function(res) {
                    console.log(res.data[options.addressIndex])
                },
            })
        }
    },
    checkPhoneAndPostCode(data) {
        let phoneReg = /^1[3|4|5|8][0-9]\d{4,8}$/;
        let postReg = /[1-9]\d{5}(?!\d)/;
        return phoneReg.test(data.phone) && postReg.test(data.post_code)
    }
})